// pages/spelling/spelling.js
const wordsData = {
  "animals": [
    {"word": "cat", "chinese": "猫", "image": "/images/words/cat.png", "sound": "/sounds/word-cat.mp3"},
    {"word": "dog", "chinese": "狗", "image": "/images/words/dog.png", "sound": "/sounds/word-dog.mp3"},
    {"word": "bird", "chinese": "鸟", "image": "/images/words/bird.png", "sound": "/sounds/word-bird.mp3"},
    {"word": "fish", "chinese": "鱼", "image": "/images/words/fish.png", "sound": "/sounds/word-fish.mp3"},
    {"word": "rabbit", "chinese": "兔子", "image": "/images/words/rabbit.png", "sound": "/sounds/word-rabbit.mp3"},
    {"word": "tiger", "chinese": "老虎", "image": "/images/words/tiger.png", "sound": "/sounds/word-tiger.mp3"},
    {"word": "lion", "chinese": "狮子", "image": "/images/words/lion.png", "sound": "/sounds/word-lion.mp3"},
    {"word": "elephant", "chinese": "大象", "image": "/images/words/elephant.png", "sound": "/sounds/word-elephant.mp3"}
  ],
  "fruits": [
    {"word": "apple", "chinese": "苹果", "image": "/images/words/apple.png", "sound": "/sounds/word-apple.mp3"},
    {"word": "banana", "chinese": "香蕉", "image": "/images/words/banana.png", "sound": "/sounds/word-banana.mp3"},
    {"word": "orange", "chinese": "橙子", "image": "/images/words/orange.png", "sound": "/sounds/word-orange.mp3"},
    {"word": "grape", "chinese": "葡萄", "image": "/images/words/grape.png", "sound": "/sounds/word-grape.mp3"},
    {"word": "strawberry", "chinese": "草莓", "image": "/images/words/strawberry.png", "sound": "/sounds/word-strawberry.mp3"},
    {"word": "watermelon", "chinese": "西瓜", "image": "/images/words/watermelon.png", "sound": "/sounds/word-watermelon.mp3"},
    {"word": "pear", "chinese": "梨", "image": "/images/words/pear.png", "sound": "/sounds/word-pear.mp3"},
    {"word": "peach", "chinese": "桃子", "image": "/images/words/peach.png", "sound": "/sounds/word-peach.mp3"}
  ],
  "colors": [
    {"word": "red", "chinese": "红色", "image": "/images/words/red.png", "sound": "/sounds/word-red.mp3"},
    {"word": "blue", "chinese": "蓝色", "image": "/images/words/blue.png", "sound": "/sounds/word-blue.mp3"},
    {"word": "green", "chinese": "绿色", "image": "/images/words/green.png", "sound": "/sounds/word-green.mp3"},
    {"word": "yellow", "chinese": "黄色", "image": "/images/words/yellow.png", "sound": "/sounds/word-yellow.mp3"},
    {"word": "orange", "chinese": "橙色", "image": "/images/words/orange-color.png", "sound": "/sounds/word-orange.mp3"},
    {"word": "purple", "chinese": "紫色", "image": "/images/words/purple.png", "sound": "/sounds/word-purple.mp3"},
    {"word": "pink", "chinese": "粉色", "image": "/images/words/pink.png", "sound": "/sounds/word-pink.mp3"},
    {"word": "black", "chinese": "黑色", "image": "/images/words/black.png", "sound": "/sounds/word-black.mp3"}
  ],
  "numbers": [
    {"word": "one", "chinese": "一", "number": 1, "image": "/images/words/one.png", "sound": "/sounds/word-one.mp3"},
    {"word": "two", "chinese": "二", "number": 2, "image": "/images/words/two.png", "sound": "/sounds/word-two.mp3"},
    {"word": "three", "chinese": "三", "number": 3, "image": "/images/words/three.png", "sound": "/sounds/word-three.mp3"},
    {"word": "four", "chinese": "四", "number": 4, "image": "/images/words/four.png", "sound": "/sounds/word-four.mp3"},
    {"word": "five", "chinese": "五", "number": 5, "image": "/images/words/five.png", "sound": "/sounds/word-five.mp3"},
    {"word": "six", "chinese": "六", "number": 6, "image": "/images/words/six.png", "sound": "/sounds/word-six.mp3"},
    {"word": "seven", "chinese": "七", "number": 7, "image": "/images/words/seven.png", "sound": "/sounds/word-seven.mp3"},
    {"word": "eight", "chinese": "八", "number": 8, "image": "/images/words/eight.png", "sound": "/sounds/word-eight.mp3"},
    {"word": "nine", "chinese": "九", "number": 9, "image": "/images/words/nine.png", "sound": "/sounds/word-nine.mp3"},
    {"word": "ten", "chinese": "十", "number": 10, "image": "/images/words/ten.png", "sound": "/sounds/word-ten.mp3"}
  ]
};

Page({
  data: {
    allWords: [],
    currentWord: null,
    currentWordIndex: 0,
    answerSlots: [],
    availableLetters: [],
    currentSound: '',
    showResult: false,
    resultIcon: '',
    resultText: '',
    showNext: false,
    isAnswerComplete: false,
    audioContext: null
  },

  onLoad() {
    // 创建音频上下文
    this.audioContext = wx.createInnerAudioContext();
    
    // 初始化题目
    this.initWords();
  },

  onShow() {
    // 每次显示页面时重新打乱题目
    this.initWords();
  },

  initWords() {
    // 合并所有分类的单词
    const allWords = [];
    Object.keys(wordsData).forEach(category => {
      allWords.push(...wordsData[category]);
    });
    
    // 每次重新打乱
    this.setData({
      allWords: this.shuffleArray([...allWords]),
      currentWordIndex: 0
    });
    
    // 开始第一题
    this.startNewWord();
  },

  onUnload() {
    if (this.audioContext) {
      this.audioContext.destroy();
    }
  },

  // 打乱数组
  shuffleArray(array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  },

  // 开始新单词
  startNewWord() {
    const word = this.data.allWords[this.data.currentWordIndex];
    if (!word) return;
    
    const wordLetters = word.word.split('');
    
    // 创建答案槽位（确保每个槽位都是对象）
    const answerSlots = wordLetters.map(() => ({ letter: '' }));
    
    // 将单词的字母拆分成独立的字母，并打乱顺序（不添加干扰字母）
    let availableLetters = wordLetters.map(letter => ({
      letter: letter.toUpperCase(),
      used: false
    }));
    
    // 打乱字母顺序（注意：shuffleArray 返回新数组）
    availableLetters = this.shuffleArray(availableLetters);
    
    // 如果是数字类型，为当前单词添加 circles 数组
    let currentWord = { ...word };
    if (word.number !== undefined) {
      currentWord.circles = Array(word.number).fill(0);
    }
    
    console.log('开始新单词', word.word, { answerSlots, availableLetters });
    
    this.setData({
      currentWord: currentWord,
      answerSlots: answerSlots,
      availableLetters: availableLetters,
      showResult: false,
      showNext: false,
      isAnswerComplete: false,
      currentSound: word.sound
    }, () => {
      console.log('新单词数据设置完成', this.data.answerSlots, this.data.availableLetters);
    });
  },

  // 点击选择字母
  selectLetter(e) {
    const index = parseInt(e.currentTarget.dataset.index);
    const letter = this.data.availableLetters[index];
    
    // 如果字母不存在或已被使用，则忽略
    if (!letter || letter.used) {
      console.log('字母不存在或已被使用', index, letter);
      return;
    }
    
    // 找到第一个空槽位
    const emptyIndex = this.data.answerSlots.findIndex(slot => !slot.letter || slot.letter === '');
    if (emptyIndex !== -1) {
      this.placeLetterInSlot(index, emptyIndex);
    } else {
      console.log('没有空槽位了');
    }
  },

  // 将字母放入槽位
  placeLetterInSlot(letterIndex, slotIndex) {
    const letter = this.data.availableLetters[letterIndex];
    if (!letter || letter.used) {
      console.log('字母无效或已使用', letterIndex, letter);
      return;
    }
    
    console.log('放置字母', letter.letter, '到槽位', slotIndex);
    
    // 创建新的答案槽位数组（深拷贝）
    const answerSlots = this.data.answerSlots.map((slot, idx) => {
      if (idx === slotIndex) {
        return { letter: letter.letter };
      }
      return { letter: slot.letter || '' };
    });
    
    // 创建新的可用字母数组（深拷贝）
    const availableLetters = this.data.availableLetters.map((l, idx) => {
      if (idx === letterIndex) {
        return { letter: l.letter, used: true };
      }
      return { letter: l.letter, used: l.used || false };
    });
    
    const isComplete = answerSlots.every(slot => slot.letter && slot.letter !== '');
    
    console.log('更新数据', { answerSlots, availableLetters, isComplete });
    
    this.setData({
      answerSlots: answerSlots,
      availableLetters: availableLetters,
      isAnswerComplete: isComplete
    }, () => {
      console.log('数据更新完成', this.data.answerSlots);
    });
    
    // 如果填满了，自动检查答案（延迟一下让用户看到效果）
    if (isComplete) {
      setTimeout(() => {
        this.checkAnswer();
      }, 500);
    }
  },

  // 移除字母（点击答案槽位可移除已放置的字母）
  removeLetter(e) {
    const slotIndex = e.currentTarget.dataset.index;
    const slot = this.data.answerSlots[slotIndex];
    
    if (!slot.letter) return;
    
    // 找到对应的字母并恢复
    const letterIndex = this.data.availableLetters.findIndex(
      (l, i) => l.letter === slot.letter && l.used
    );
    
    if (letterIndex !== -1) {
      const answerSlots = [...this.data.answerSlots];
      answerSlots[slotIndex] = { letter: '' };
      
      const availableLetters = [...this.data.availableLetters];
      availableLetters[letterIndex].used = false;
      
      const isComplete = answerSlots.every(s => s.letter);
      
      this.setData({
        answerSlots,
        availableLetters,
        isAnswerComplete: isComplete,
        showResult: false
      });
    }
  },

  // 检查答案
  checkAnswer() {
    const userAnswer = this.data.answerSlots.map(slot => slot.letter).join('').toLowerCase();
    const correctAnswer = this.data.currentWord.word.toLowerCase();
    
    const isCorrect = userAnswer === correctAnswer;
    
    // 更新记录
    const app = getApp();
    app.updateRecords('spelling', isCorrect);
    
    this.setData({
      showResult: true,
      resultIcon: isCorrect ? '✅' : '❌',
      resultText: isCorrect ? '太棒了！答对了！' : `正确答案是：${correctAnswer.toUpperCase()}`,
      showNext: true
    });
  },

  // 处理结果
  handleResult() {
    this.setData({
      showResult: false
    });
    
    if (this.data.showNext) {
      this.nextWord();
    }
  },

  // 下一题
  nextWord() {
    const nextIndex = (this.data.currentWordIndex + 1) % this.data.allWords.length;
    this.setData({
      currentWordIndex: nextIndex
    });
    this.startNewWord();
  },

  // 重新开始
  resetGame() {
    this.setData({
      currentWordIndex: 0,
      allWords: this.shuffleArray([...this.data.allWords])
    });
    this.startNewWord();
  },

  // 播放提示
  playHint() {
    if (this.audioContext && this.data.currentWord) {
      this.audioContext.src = this.data.currentWord.sound;
      this.audioContext.play();
    }
  },

  onAudioEnd() {
    // 音频播放结束
  }
});

